package fr.resasante.utils;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.jboss.logging.Logger;

public final class ServicesUtils {
	/**
	 * ServiceUtils class instance
	 */
	private static volatile ServicesUtils instance = null;

	/**
	 * The context
	 */
	private InitialContext contexte = null;

	/**
	 * The logger
	 */
	private static final Logger logger = Logger.getLogger(ServicesUtils.class.getName());

	/**
	 * Constructor
	 * 
	 * @throws NamingException
	 */
	private ServicesUtils() throws NamingException {
		super();
		initServices();
	}

	/**
	 * Method returning a Singleton class instance
	 * 
	 * @return Singleton instance
	 * @throws NamingException
	 */
	public final static ServicesUtils getInstance() throws NamingException {
		if (ServicesUtils.instance == null) {
			synchronized (ServicesUtils.class) {
				if (ServicesUtils.instance == null) {
					ServicesUtils.instance = new ServicesUtils();
				}
			}
		}
		return ServicesUtils.instance;
	}

	/**
	 * Init EJB services
	 * 
	 * @throws NamingException
	 */
	private void initServices() throws NamingException {
		contexte = new InitialContext();
	}

	/**
	 * Call an EJB service
	 * 
	 * @param serviceName
	 *            The service name in the EJB
	 * @return The result of the EJB call
	 * @throws NamingException
	 */
	public Object callService(String serviceName) throws NamingException {
		final String earName = PropertiesUtils.getInstance().getProperty("ear.name");
		final String ejbName = PropertiesUtils.getInstance().getProperty("ejb.name");
		String jndiBinding = "java:global/" + earName + "/" + ejbName + "/" + serviceName
				+ "!fr.resasante.ejb.service." + serviceName + "Remote";
		logger.debug(jndiBinding);
		return contexte.lookup(jndiBinding);
	}
}